package com.tenement.handler;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tenement.config.SecurityConfig;
import com.tenement.service.UserTenementService;
import com.tenement.utils.JwtUtil;
import com.tenement.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RequiredArgsConstructor
@Component
public class TenantInterceptor implements HandlerInterceptor {

    private final UserTenementService userTenementService;

    private final RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtUtil.TOKEN_AUTHORIZATION);
        if (Arrays.asList(SecurityConfig.AUTH_WHITELIST).contains(request.getServletPath())) {return true;}
        if (StrUtil.isBlank(token)) {
            List<Long> tenementIds = new ArrayList<>();
            tenementIds.add(1L);
            request.setAttribute("tenantId", tenementIds);
            return true;
        }
        try {
            Claims claims = JwtUtil.parseJWT(token);
            if (ObjectUtil.isNotNull(token)) {
                List<Long> tenementIds = userTenementService.tenementIds(Long.valueOf(claims.getSubject()));
                if (CollectionUtil.isEmpty(tenementIds)) {
                    tenementIds = new ArrayList<>();
                    tenementIds.add(1L);
                }
                request.setAttribute("tenantId", tenementIds);
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        return true;
    }
}
